﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using VSSTQH.Properties;
using VSSTQH.DataAccess;
using VSSTQH.Reports;
using System.IO;

namespace VSSTQH
{
    public partial class FrmMDI : Form
    {
        private bool _isCorrectConnection = false;
        public Timer timer;

        #region Singleton Members
        private static volatile FrmMDI instance;
        private static object syncRoot = new Object();

        public static FrmMDI Instance
        {
            get
            {

                if (instance == null)
                {
                    instance = new FrmMDI();
                }

                return instance;
            }
        }

        #endregion

        #region Ctors
        private FrmMDI()
        {
            InitializeComponent();
            IConnection dataAccess = new Connection();
            if (SystemInformation.Network)
            {
                
                    if (dataAccess.CheckDatabases())
                    {
                        _isCorrectConnection = true;
                        Initialize();
                    }
                    
               
            }
            else
            {
                MessageBox.Show("Kết nối mạng không được tìm thấy. Kiểm tra lại","Chú ý",MessageBoxButtons.OK);
            }

            // Test
            //_isCorrectConnection = true;
            //Initialize();
        }
        #endregion

        #region Methods
        public void Initialize()
        {
            //this.btnChangePassword.Click += new CommandEventHandler(ClickButtonOpenFile);
            //this.btnConfiguration.Click += new CommandEventHandler(ClickButtonOpenFile);
            // Click button Open Files
            //this.buttonBar1.ItemClick += new Janus.Windows.ButtonBar.ItemEventHandler(buttonBar1_ItemClick);

            // System
            this.ConfigMenuItem.Click += new EventHandler(MenuItem_Click);
            this.UserMenuItem.Click += new EventHandler(MenuItem_Click);
            this.LogoutMenuItem.Click += new EventHandler(MenuItem_Click);
            this.ChangePasswordMenuItem.Click += new EventHandler(MenuItem_Click);

            this.ExitMenuItem.Click += new EventHandler(MenuItem_Click);

            // PO
            this.PoMenuItem.Click += new EventHandler(MenuItem_Click);
            this.PoListMenuItem.Click += new EventHandler(MenuItem_Click);
            this.InventoryMenuItem.Click += new EventHandler(MenuItem_Click);

            // List
            this.VendorMenuItem.Click += new EventHandler(MenuItem_Click);
            this.ProductMenuItem.Click += new EventHandler(MenuItem_Click);

            // Report
            this.ReportDateMenuItem.Click += new EventHandler(MenuItem_Click);
            //this.ReportProductMenuItem.Click += new EventHandler(MenuItem_Click);
            //this.ReportVendorMenuItem.Click += new EventHandler(MenuItem_Click);

            this.Size = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height - 30);
            this.Location = new Point(0, 0);

            // Set timer
            timer = new Timer();
            timer.Tick += new EventHandler(delegate
            {
                labelCommand.Text = DateTime.Now.ToString();
            });
            timer.Start();
        }

        protected override void OnClosed(EventArgs e)
        {
            timer.Stop();
            timer.Dispose();

            base.OnClosed(e);
        }

        void MenuItem_Click(object sender, EventArgs e)
        {
            switch ((sender as ToolStripMenuItem).Name)
            {
                case "ConfigMenuItem":
                    FrmConfiguration.Instance.MdiParent = this;
                    FrmConfiguration.Instance.Show();
                    break;
                case "UserMenuItem":
                    FrmUsers.Instance.MdiParent = this;
                    FrmUsers.Instance.Show();
                    break;
                case "LogoutMenuItem":
                    foreach (var f in this.MdiChildren.Where(c => !c.IsDisposed))
                    {
                        f.Close();
                    }
                    this.OnLoad(null);
                    break;
                case "ChangePasswordMenuItem":
                    FrmChangePassword.Instance.MdiParent = this;
                    FrmChangePassword.Instance.Show();
                    break;
                case "PoMenuItem":
                    FrmPO frmPo = new FrmPO();
                    frmPo.MdiParent = this;
                    frmPo.Show();
                    break;
                case "PoListMenuItem":
                    FrmPOList.Instance.MdiParent = this;
                    FrmPOList.Instance.Show();
                    break;
                case "InventoryMenuItem":
                    FrmWarehouse frmWareHouse = new FrmWarehouse();
                    frmWareHouse.MdiParent = this;
                    frmWareHouse.Show();
                    break;

                    //try
                    //{
                    //    bool? result = Common.ShowYesNoQuestion("Bạn có chắc sẽ thực hiện nhập kho hay không?");
                    //    if (result.HasValue && result.Value)
                    //    {
                    //        DirectoryInfo dir = new DirectoryInfo(Settings.Default.MM_S2C);
                    //        foreach (var item in dir.GetFiles("*.csv"))
                    //        {
                    //            File.Move(item.FullName, Settings.Default.Stored + "\\MM_S2C\\" + item.Name);
                    //        }

                    //        dir = new DirectoryInfo(Settings.Default.MM_C2S);
                    //        foreach (var item in dir.GetFiles("*.csv"))
                    //        {
                    //            File.Move(item.FullName, Settings.Default.Stored + "\\SD_S2C\\" + item.Name);
                    //        }

                    //        dir = new DirectoryInfo(Settings.Default.SD_S2C);
                    //        foreach (var item in dir.GetFiles("*.csv"))
                    //        {
                    //            File.Move(item.FullName, Settings.Default.Stored + "\\MM_C2S\\" + item.Name);
                    //        }

                    //        dir = new DirectoryInfo(Settings.Default.SD_C2S);
                    //        foreach (var item in dir.GetFiles("*.csv"))
                    //        {
                    //            File.Move(item.FullName, Settings.Default.Stored + "\\SD_C2S\\" + item.Name);
                    //        }

                    //        Common.ShowSuccessful("Chuyển file từ thư mục {0} và {1} vào thư mục {2} thành công!", Settings.Default.MM_S2C, Settings.Default.SD_S2C, Settings.Default.Stored);
                    //    }
                    //    else
                    //    {
                    //        Common.ShowSuccessful("Chuyển file từ thư mục {0} và {1} vào thư mục {2} không thành công!", Settings.Default.MM_S2C, Settings.Default.SD_S2C, Settings.Default.Stored);
                    //    }
                    //}
                    //catch (Exception ex)
                    //{
                    //    Common.ShowAlert(ex.Message);
                    //}
                    //break;
                case "VendorMenuItem":
                    FrmVendor.Instance.MdiParent = this;
                    FrmVendor.Instance.Show();
                    break;
                case "ProductMenuItem":
                    FrmProducts.Instance.MdiParent = this;
                    FrmProducts.Instance.Show();
                    break;
                case "ReportDateMenuItem":
                    FrmViewReport frmReport = new FrmViewReport();
                    frmReport.MdiParent = this;
                    frmReport.Show();
                    break;
                //case "ReportProductMenuItem":
                //    break;
                //case "ReportVendorMenuItem":
                //    break;
                case "ExitMenuItem":
                    Application.Exit();
                    break;
            }
        }

        #endregion

        #region Events
        //void ClickButtonOpenFile(object sender, Janus.Windows.Ribbon.CommandEventArgs e)
        //{
        //    ButtonCommand button = sender as ButtonCommand;
        //    switch (button.Name)
        //    {
        //        case "btnChangePassword":
        //            FrmChangePassword.Instance.MdiParent = this;
        //            FrmChangePassword.Instance.Show();
        //            FrmChangePassword.Instance.Activate();
        //            break;
        //        case "btnConfiguration":
        //            FrmConfiguration.Instance.MdiParent = this;
        //            FrmConfiguration.Instance.Show();
        //            FrmConfiguration.Instance.Activate();
        //            break;
        //    }
        //}

        protected override void OnLoad(EventArgs e)
        {
            if (_isCorrectConnection)
            {
                // Correct connection
                FrmLogin login = new FrmLogin();
                if (login.ShowDialog() != DialogResult.OK)
                {
                    this.Close();
                    return;
                }

                this.labelUserLogin.Text = String.Format(Resources.AccountLogin, Common.UserLogin.Username);

                // Init port to scale vehicles
                Common.InitPort();
                Common.InitPort2();
                CreateDirectory(Settings.Default.MM_S2C);
                CreateDirectory(Settings.Default.MM_C2S);
                CreateDirectory(Settings.Default.SD_S2C);
                CreateDirectory(Settings.Default.SD_C2S);
                CreateDirectory(Settings.Default.Stored + "MM_S2C");
                CreateDirectory(Settings.Default.Stored + "SD_S2C");
                CreateDirectory(Settings.Default.Stored + "MM_C2S");
                CreateDirectory(Settings.Default.Stored + "SD_C2S");

                // Set permission
                bool IsAdmin = (Common.UserLogin.GroupID == 1);
                UserMenuItem.Visible = IsAdmin;
                ListMenu.Visible = IsAdmin;
                //ReportMenu.Visible = IsAdmin;
            }
            else
            {
                Common.ShowAlert("Kết nối cơ sở dữ liệu thất bại!");
                FrmDatabase form = new FrmDatabase();
                if (form.ShowDialog() == DialogResult.OK)
                {
                    string connectionStrings = String.Empty;
                    if (form.IsWindowMode)
                    {
                        connectionStrings = String.Format(Resources.ConnectionString1, form.Server, form.Database);
                    }
                    else
                    {
                        connectionStrings = String.Format(Resources.ConnectionString2, form.Server, form.Database, form.Username, form.Password);
                    }

                    // Get the application configuration file. 
                    System.Configuration.Configuration config =
                            ConfigurationManager.OpenExeConfiguration(
                            ConfigurationUserLevel.None);

                    // Create a connection string element and 
                    // save it to the configuration file. 

                    // Create a connection string element. 
                    ConnectionStringSettings csSettings =
                            new ConnectionStringSettings("ConnectionString",
                            connectionStrings, "System.Data.SqlClient");

                    // Get the connection strings section. 
                    ConnectionStringsSection csSection =
                        config.ConnectionStrings;

                    // Add the new element. 
                    csSection.ConnectionStrings.Clear();
                    csSection.ConnectionStrings.Add(csSettings);

                    // Save the configuration file. 
                    config.Save(ConfigurationSaveMode.Modified);

                    Application.Exit();
                }
            }
            base.OnLoad(e);
        }

        void CreateDirectory(string path)
        {
            path = path.Replace("/", "\\");
            path = path.Replace("\\\\", "\\");
            string[] sPath = path.Split('\\');
            int length = sPath.Length;
            if (length > 0)
            {
                if (sPath[0].EndsWith(":"))
                {
                    string drive = sPath[0];
                    path = drive + "\\";
                    for (int i = 1; i < length; i++)
                    {
                        path += sPath[i] + "\\";
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                    }
                }
                else
                {
                    path = String.Empty;
                    for (int i = 0; i < length; i++)
                    {
                        path += sPath[i] + "\\";
                        if (!Directory.Exists(path))
                        {
                            Directory.CreateDirectory(path);
                        }
                    }
                }
            }
        }
        #endregion

    }
}
